package com.qf.realm;

import com.qf.pojo.SysUsers;
import com.qf.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;

/**
 * @author Wy
 * @version V1.0
 * @Project MavenDemo
 * @Package com.qf.realm
 * @Description:
 * @Date 2022/6/13 20:52
 */
public class MyUserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("=========自定义Realm,==doGetAuthorizationInfo方法, 授权: 根据用户名获取用户的角色权限数据赋予这个用户==============");
        //1. 获取认证的时候shiro框架中session存储的用户对象
        SysUsers users = (SysUsers) principalCollection.getPrimaryPrincipal();
        int id = users.getId();
        //2. 根据用户id, 到数据库角色表中获取用户的角色信息
        Set<String> rolesByUid = userService.findRolesByUid(id);
        //3.
        Set<String> permByuid = userService.findPermByuid(id);
        //4. 封装shiro规定的角色权限对象
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //5. 将角色数据赋予shiro的权限对象
        simpleAuthorizationInfo.setRoles(rolesByUid);
        //6. 将权限数据赋予shiro的权限对象
        simpleAuthorizationInfo.setStringPermissions(permByuid);

        //7. 返回shiro的权限对象给, securityManager核心对象
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("================自定义Realm, doGetAuthenticationInfo方法, 登录认证, 判断用户名密码是否正确==========================");
        //1获取用户在登录界面输入的用户名
       String userName = (String) token.getPrincipal();
       //2.获取用户在登录界面输入的密码
        String password =new String((char[])token.getCredentials());
        //3.根据用户名到数据里面获取用户对象
        SysUsers user = userService.findUserByName(userName);
        //4. 如果用户对象获取不到, 抛异常, 用户不存在
        if(user==null){
            throw new UnknownAccountException("用户不存在");
        }
        if(!password.equals(user.getPassword())){
            //6. 如果密码不对抛异常, 密码错误
            throw  new IncorrectCredentialsException("密码不正确");
        }

        //7. 如果密码正确, 封装返回的用户对象给shiro框架的Securitymanager核心
        //第一参数:用户对象, 第二参数:密码, 第三参数: 当前自定义realm对象的名称
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, this.getName());
        return info;
    }
}
